package com.weitu.worklicense.controller;

import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.worklicense.entity.FireLicense;
import com.weitu.worklicense.entity.FireLicenseCriteria;
import com.weitu.worklicense.entity.WorkLicenseApply;
import com.weitu.worklicense.entity.WorkLicenseApplyCriteria;
import com.weitu.worklicense.service.FireLicenseService;
import com.weitu.worklicense.service.WorkLicenseApplyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/5/25
 */
@Controller
@RequestMapping(value = "workLicense/apply")
public class WorkLicenseApplyController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "workLicense/apply";
    private final WorkLicenseApplyService workLicenseApplyService;
    private final FireLicenseService fireLicenseService;
    private final DataAuthorityService dataAuthorityService;
    private final AccessoryUtilService accessoryUtilService;

    @Autowired
    public WorkLicenseApplyController(WorkLicenseApplyService workLicenseApplyService
            , FireLicenseService fireLicenseService
            , DataAuthorityService dataAuthorityService
            , AccessoryUtilService accessoryUtilService) {
        this.workLicenseApplyService = workLicenseApplyService;
        this.fireLicenseService = fireLicenseService;
        this.dataAuthorityService = dataAuthorityService;
        this.accessoryUtilService = accessoryUtilService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/view";
    }

    @RequestMapping(value = "/simpleList", method = RequestMethod.GET)
    public String simpleList() {
        return MODULE_BATH_PATH + "/simpleList";
    }

    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) {
        WorkLicenseApplyCriteria criteria = new WorkLicenseApplyCriteria();
        WorkLicenseApplyCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0);
        putSearchCriteria(cr);

        int count = workLicenseApplyService.countByCriteria(criteria);
        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<WorkLicenseApply> workLicenseApplies = workLicenseApplyService.selectByCriteria(criteria);
        return dataGridPagination.flushDataGridData(workLicenseApplies);
    }

    @SystemLog(module = "作业许可申请", methods = "新增作业许可申请信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(WorkLicenseApply workLicenseApply) {
        String id = IDGenerator.getId();
        workLicenseApply.setId(id);
        addCreateAttribute(workLicenseApply);

        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (workLicenseApplyService.insertSelective(workLicenseApply) > 0) {
                return success("保存成功！", workLicenseApply);
            } else {
                return fail("附件保存失败！");
            }
        } else {
            return fail("保存失败！");
        }
    }

    @SystemLog(module = "作业许可申请", methods = "修改作业许可申请信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(WorkLicenseApply workLicenseApply) {
        String id = workLicenseApply.getId();
        addUpdateAttribute(workLicenseApply);
        if (workLicenseApply.getIsCheckContractor() == 1) {
            workLicenseApply.setDeptId(null);
            workLicenseApply.setDeptName(null);
        } else {
            workLicenseApply.setContractorAuditId(null);
        }
        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (workLicenseApplyService.updateByPrimaryKey(workLicenseApply) > 0) {
                return success("保存成功！", workLicenseApply);
            } else {
                return fail("附件保存失败！");
            }
        } else {
            return fail("保存失败！");
        }
    }

    @SystemLog(module = "作业许可申请", methods = "删除作业许可申请信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) {
        if (workLicenseApplyService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/countByNotAudited", method = RequestMethod.POST)
    public AjaxResult countByNotAuditedAjax() {
        int num = workLicenseApplyService.countByNotAudited();
        return success("数据获取成功！", num);
    }

    @ResponseBody
    @RequestMapping(value = "/countByNotHandled", method = RequestMethod.POST)
    public AjaxResult countByNotHandledAjax() {
        int num = workLicenseApplyService.countByNotHandled();
        return success("数据获取成功！", num);
    }

    @ResponseBody
    @RequestMapping(value = "/countByWorkType", method = RequestMethod.POST)
    public AjaxResult countByWorkTypeAjax() {
        List<Map> num = workLicenseApplyService.countByWorkType();
        return success("数据获取成功！", num);
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(WorkLicenseApplyCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("workLevelId"))) {
            criteria.andWorkLevelIdEqualTo(getPara("workLevelId"));
        }
        if (StringUtils.isNotEmpty(getPara("workTypeId"))) {
            criteria.andWorkTypeIdEqualTo(getPara("workTypeId"));
        }
        if (StringUtils.isNotEmpty(getPara("applyUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("applyUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("applyDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("applyDeptId"));
        }
        if (StringUtils.isNotEmpty(getPara("planStartDate"))) {
            criteria.andPlanStartDateEqualTo(getPara("planStartDate"));
        }
        if (StringUtils.isNotEmpty(getPara("planEndDate"))) {
            criteria.andPlanEndDateEqualTo(getPara("planEndDate"));
        }
        if (StringUtils.isNotEmpty(getPara("applyDateMin"))) {
            criteria.andApplyDateGreaterThanOrEqualTo(getPara("applyDateMin"));
        }
        if (StringUtils.isNotEmpty(getPara("applyDateMax"))) {
            criteria.andApplyDateLessThanOrEqualTo(getPara("applyDateMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        if (getParaToInt("filter", 0) == 1) {
            filterApplyList(criteria);
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }

    /**
     * 选择申请时筛选列表
     *
     * @param criteria 条件实体
     */
    private void filterApplyList(WorkLicenseApplyCriteria.Criteria criteria) {
        FireLicenseCriteria example = new FireLicenseCriteria();
        example.createCriteria().andDelStateEqualTo(0);
        List<FireLicense> fireLicenses = fireLicenseService.selectByCriteria(example);
        if (fireLicenses != null && !fireLicenses.isEmpty()) {
            List<String> applyIds = new ArrayList<String>();
            for (FireLicense fireLicense : fireLicenses) {
                applyIds.add(fireLicense.getApplyId());
            }
            String applyId = getPara("applyId");
            if (StringUtils.isNotEmpty(applyId)) {
                applyIds.remove(applyId);
            }
            if (!applyIds.isEmpty()) {
                criteria.andIdNotIn(applyIds);
            }
        }
    }

    /**
     * 向页面实体添加属性
     *
     * @param model 页面实体
     * @param id    主键id
     */
    private void putModelAttributes(Model model, String id) {
        WorkLicenseApply workLicenseApply = workLicenseApplyService.selectByPrimaryKey(id);
        model.addAttribute("accessoryList", accessoryUtilService.queryAccessoryByBusinessId(id));
        model.addAttribute("workLicenseApply", workLicenseApply);
    }

    /**
     * 添加登记人、登记时间和部门信息
     *
     * @param entity 实体
     */
    private void addCreateAttribute(WorkLicenseApply entity) {
        entity.setAddUserId(getSessionUser().getId());
        entity.setAddDeptId(getSessionUser().getDepartment().getId());
        entity.setAddTime(DateTimeUtil.formatterDateTime());
    }

    /**
     * 添加修改人、修改时间和部门信息
     *
     * @param entity 实体
     */
    private void addUpdateAttribute(WorkLicenseApply entity) {
        entity.setUpdateUserId(getSessionUser().getId());
        entity.setUpdateDeptId(getSessionUser().getDepartment().getId());
        entity.setUpdateTime(DateTimeUtil.formatterDateTime());
    }
}
